package com.huawei.app.demo.video;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.view.SurfaceHolder;

import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.httpapi.ThreadPools;

/**
 * 点对点共享屏幕Surface窗口回调处理
 *
 * @since 2021-03-01
 */
public class ShareScreenRecvSurfaceCallback implements SurfaceHolder.Callback {

    private static final String TAG = ShareScreenRecvSurfaceCallback.class.getSimpleName();

    private ReceiverTask receiverTask;
    private AvcDecoderTask decoderTask;

    public ShareScreenRecvSurfaceCallback(ReceiverTask receiverTask, AvcDecoderTask decoderTask) {
        this.receiverTask = receiverTask;
        this.decoderTask = decoderTask;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        LogUtils.getInstance().i(TAG, "surfaceCreated begin.");

        // holder.setFormat(PixelFormat.TRANSPARENT);
        this.decoderTask.setOutputSurface(holder.getSurface());
        this.decoderTask.initDecoder();
        ThreadPools.run(this.receiverTask);
        ThreadPools.run(this.decoderTask);

        LogUtils.getInstance().i(TAG, "surfaceCreated end.");
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        LogUtils.getInstance().i(TAG, "surfaceDestroyed begin.");

        if (this.receiverTask != null) {
            this.receiverTask.stop();
            this.receiverTask = null;
        }
        if (this.decoderTask != null) {
            this.decoderTask.stop();
            this.decoderTask = null;
        }
        LogUtils.getInstance().i(TAG, "surfaceDestroyed end.");
    }

    private void initDraw(SurfaceHolder holder, int width, int height) {
        Canvas canvas = holder.lockCanvas();
        if (canvas == null) {
            return;
        }

        String tip = "waiting...";
        Paint p = new Paint();
        p.setTextSize(64);
        p.setColor(Color.GREEN);
        int txtWidth = (int)p.measureText(tip);
        canvas.drawText(tip, width / 2 - txtWidth / 2, height / 2, p);

        holder.unlockCanvasAndPost(canvas);
    }
}
